package com.link.base.base.coupons.service;

import com.alibaba.fastjson.JSONObject;
import com.link.base.base.coupons.model.*;
import com.link.base.core.basic.util.YmlConstants;
import com.link.base.user.model.CoreUser;
import com.link.base.base.user.model.User;
import com.link.base.base.accnt.dao.mybatis.mapper.AccountMapper;
import com.link.base.base.accnt.model.Account;
import com.link.base.base.accnt.model.AppOrderInfo;
import com.link.base.base.accnt.service.AccountService;
import com.link.base.base.coupons.dao.mybatis.mapper.BrandSeriesMapper;
import com.link.base.base.coupons.dao.mybatis.mapper.CollectRecordMapper;
import com.link.base.base.coupons.dao.mybatis.mapper.CouponsMapper;
import com.link.base.base.coupons.dao.mybatis.mapper.ProCouponsMapper;
import com.link.base.base.order.model.SaleOrder;
import com.link.base.base.order.model.SaleOrderItem;
import com.link.base.base.order.service.SaleOrderItemService;
import com.link.base.base.order.service.SaleOrderService;
import com.link.base.base.product.dao.mybatis.mapper.ProductMapper;
import com.link.base.base.product.model.Product;
import com.link.base.base.product.service.ProductService;
import com.link.base.base.saleactivity.model.SaleActivity;
import com.link.base.base.saleactivity.service.SaleActivityService;
import com.link.base.base.sms.service.PushSmsService;
import com.link.base.base.user.service.UserService;
import com.link.base.base.wechat.service.ArticlesService;
import com.link.core.cllog.LCLogger;
import com.link.base.wechat.basic.util.WeixinHttpUtil;
import com.link.base.wechat.wxplatform.model.WxPlatform;
import com.link.base.wechat.wxplatform.service.WxPlatformService;
import com.link.base.wechat.wxtoken.service.WxTokenService;
import com.link.core.basic.dao.mapper.BasicMapper;
import com.link.core.basic.interceptor.SecurityInterceptor;
import com.link.core.basic.query.QueryParams;
import com.link.core.basic.service.BasicServiceImpl;
import com.link.core.basic.service.ServiceException;
import com.link.core.util.*;
import com.link.core.util.redisclient.LinkRedisClient;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>优惠券</p>
 *
 * @author wangdawei
 * @date 2018/6/8
 */

@Service
public class CouponsServiceImpl extends BasicServiceImpl<Coupons> implements CouponsService {

    /**
     * Redis缓存key值后缀
     */
    private static final String VCODECACHE_KEYSUFFIX = "#CampaignAcctSourceFromVCode";
    /**
     * 有效时间
     */
    private static final int VCODE_EFFECTIVETIME = 2;

    @Resource
    private CouponsMapper couponsMapper;
    @Resource
    private AccountService accountService;
    @Resource
    private Environment env;
    @Resource
    private CollectRecordService collectRecordService;

    @Resource
    private CollectRecordMapper collectRecordMapper;

    @Resource
    private ProductMapper productMapper;

    @Resource
    private ProCouponsMapper proCouponsMapper;

    @Resource
    private BrandSeriesMapper brandSeriesMapper;

    @Resource
    private PushSmsService pushSmsService;

    @Resource
    private ArticlesService articlesService;

    @Resource
    private WxPlatformService wxPlatformService;

    @Resource
    private SaleOrderService saleOrderService;

    @Resource
    private SaleOrderItemService saleOrderItemService;

    @Resource
    private UserService userService;

    @Resource
    private SaleActivityService saleActivityService;

    @Resource
    private AccountMapper accountMapper;

    @Resource
    private ProductService productService;

    @Resource
    private WxTokenService wxTokenService;

    @Override
    public BasicMapper<Coupons> getBasicMapper() {
        return couponsMapper;
    }

    @Override
    public List<Coupons> queryAcctByExamplePage(Coupons entity) throws Exception {
        return couponsMapper.queryAcctByExamplePage(entity);
    }

    /**
     * 按类型查询优惠卷列表（门店商）
     *
     * @param entity 礼品对象
     * @return 优惠券列表
     * @throws Exception 异常
     * @author : wangdawei
     * @date : 2018/5/2
     */
    @Override
    public List<Coupons> queryCoupListByExamplePage(Coupons entity) throws Exception {
        return couponsMapper.queryCoupListByExamplePage(entity);
    }

    /**
     * 按类型查询优惠卷列表（渠道商）
     *
     * @param entity 礼品对象
     * @return 优惠券列表
     * @throws Exception 异常
     * @author : wangdawei
     * @date : 2018/5/2
     */
    @Override
    public List<Coupons> queryCeCoupListByExamplePage(Coupons entity) throws Exception {
        return couponsMapper.queryCeCoupListByExamplePage(entity);
    }

    /**
     * 校验该客户是否已经领取过优惠券
     * @author : wangdawei
     * @param entity 优惠券对象
     * @param acct   活动客户
     * @throws Exception 异常
     * @date : 2018/11/22
     */

    private void checkCoupons(Account acct, Coupons entity) throws Exception {
        acct.setAttr1("mobilePhone");
        List<Account> accountList = accountService.queryAcctListById(acct);
        Boolean flag1 = false;
        for (Account account : accountList) {
            CollectRecord collectRecord = new CollectRecord();
            collectRecord.setCouponsId(entity.getId());
            collectRecord.setAccntId(account.getId());
            collectRecord.setPageFlag(false);
            List<CollectRecord> collectRecordList = collectRecordService.queryByExamplePage(collectRecord);
            flag1 = collectRecordList.size() > 0;
            if (flag1) {
                flag1 = true;
                break;
            }
        }

        if (flag1) {
            throw new ServiceException("COUPONS-001");
        }
    }


    /**
     * 消费者直接领取优惠卷
     * @author : wangdawei
     * @param entity  优惠券对象
     * @param openId  微信openId
     * @param request
     * @return Map
     * @throws Exception 异常
     * @date : 2018/5/2
     */
    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public Map<String, Object> getCoupons(Coupons entity, String openId, HttpServletRequest request) throws Exception {
        //app领取优惠卷，获取一个默认登录用户
        Map<String, Object> result = new HashMap<String, Object>(4);

        CoreUser user = UserUtil.getUser();
        Account acct = null;
        if (user == null) {
            LCLogger.info().withMessageKey("getCoupons").withMessage("用户信息不存在,为H5客户").flush();
            user = userService.queryUserByCropId(entity.getCorpid());
            SecurityInterceptor.tempUser.set(user);
            //通过非微信渠道直接领取优惠券，获取领券客户
            acct = this.getAccnt(entity, openId, user);
        } else {
            LCLogger.info().withMessageKey("getCoupons").withMessage("用户信息存在,为小程序用户").flush();
            // 根据openid查询用户信息
            acct = new Account();
           // acct.setWxOwnOpenId(user.getOpenId());
            acct = accountService.queryConsumerByOpenId(acct);
            // 校验该用户是否已经领取过优惠券
            CollectRecord collectRecord = new CollectRecord();
            collectRecord.setCouponsId(entity.getId());
            collectRecord.setAccntId(acct.getId());
            collectRecord.setPageFlag(false);
            List<CollectRecord> collectRecordList = collectRecordService.queryByExamplePage(collectRecord);
            if (collectRecordList.size() > 0) {
                throw new ServiceException("COUPONS-002");
            }
        }
        // 根据id查询优惠券信息
        QueryParams qps = new QueryParams();
        qps.preDealSecurity(request);
        entity.setLoginCorpId(entity.getCorpid());
        Coupons coupons = queryById(entity);
        //判断优惠券是否有效
        String flag = "Y";
        //领券记录
        CollectRecord collectRecord = new CollectRecord();
        //来源导购id
        if (null != entity.getGuideId()) {
            collectRecord.setSourceGuideId(entity.getGuideId());
        }
        collectRecord.setCorpid(entity.getCorpid());
        collectRecord.setCouponsId(entity.getId());
        collectRecord.setAccntId(acct.getId());
        collectRecord.setClaimantNum(1);
        collectRecord.setClaimTime(DateUtil.dateToStr(new Date(), "yyyy-MM-dd HH:mm:ss"));
        collectRecord.setReceiveChannel(entity.getChannel());
        if (flag.equals(coupons.getIsSyn())) {
            Long id = keyGenerateService.keyGenerate();
            collectRecord.setId(id);
            collectRecord.setClaimStatus("New");
            collectRecord.setWechatCode(id.toString());
        } else {
            collectRecord.setClaimStatus("Received");
        }
        collectRecord.setPostnId(user.getPostnId());
        if (null != entity.getIssueSroreId()) {
            //添加发放门店
            collectRecord.setIssueSroreId(entity.getIssueSroreId());
        }
        String fixedTerm = "FixedTerm";
        if (StringUtils.isNotBlank(coupons.getValidityOption()) && fixedTerm.equals(coupons.getValidityOption())) {
            collectRecord.setEffectStaTime(DateUtil.dateToStr(new Date(), "yyyy-MM-dd"));
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            Date d = new Date();
            if (coupons.getEffetDay() == null) {
                coupons.setEffetDay(0);
            }
            collectRecord.setEffectEndTime(df.format(new Date(d.getTime() + (long) coupons.getEffetDay() * 24 * 60 * 60 * 1000)));
        } else {
            collectRecord.setEffectStaTime(coupons.getEffectStaTime());
            collectRecord.setEffectEndTime(coupons.getEffectEndTime());
        }
        //插入领取详情
        collectRecord.setAnonymousFlag("Y");
        collectRecordService.insert(collectRecord);
        if (flag.equals(coupons.getIsEffect())) {
            //判断优惠卷是否同步到了微信，同步则属于微信优惠卷
            String flag1 = "M";//暂时先关闭优惠券同步微信创建领取记录情况
            if (StringUtils.isNotBlank(coupons.getIsSyn()) && flag1.equals(coupons.getIsSyn())
                    && "Coupon".equals(coupons.getCouponsClass())) {
                Account account = new Account();
                //在不能获取微信openId的情况下先给openId一个默认值
                if (openId != null) {
                    //获取微信卡包accessToken
                    WxPlatform wxPlatform = new WxPlatform();
                    wxPlatform.setId(coupons.getWeChatId());
                    wxPlatform.setCorpid(entity.getCorpid());
                    wxPlatform.setLoginCorpId(entity.getCorpid());
                    WxPlatform platform = wxPlatformService.queryById(wxPlatform);
                    String accessToken = wxTokenService.getWxAccessTokenByAppId(platform.getWx_app_id()).getAccess_token();
                    result.put("result", accessToken);
                    //到微信端去创建领取记录
                    result.put("success", true);
                } else {
                    result.put("result", "领取渠道有误，请通过微信App领取");
                    result.put("success", false);
                }
            } else {
                if (coupons.getReceivedNum() == null) {
                    coupons.setReceivedNum(0);
                }
                coupons.setReceivedNum(coupons.getReceivedNum() + 1);
                coupons.setAnonymousFlag("Y");
                update(coupons);
                /*
                 * 非微信渠道领取优惠券成功之后，自动调用短信接口发送短信通知客户
                 * 发送优惠券领取中心页面
                 * */
                /************短信接口,发送短信***********/
                String prizeType = coupons.getCouponsClass();
                pushSmsService.pullDiscountCouponSendSms(prizeType, acct.getId(),
                        coupons.getCouponsName(), acct.getId() + "&&corpid=" + user.getCorpid(), user.getCorpid());
                result.put("result", collectRecord);
                result.put("success", true);
            }
        } else {
            result.put("success", false);
            result.put("result", "奖品已过期");
            throw new ServiceException("COUPONS-003");
        }
        return result;
    }

    /**
     * 根据优惠卷id获取，优惠券品牌，系列，同步微信状态等
     * @author : wangdawei
     * @param entity 优惠券对象
     * @return 优惠券对象
     * @throws Exception 异常
     * @date : 2018/5/2
     */
    @Override
    public Coupons getCouponsById(Coupons entity) throws Exception {

        if (null == entity.getId()) {
            throw new ServiceException("COUPONS-004");
        }
        Coupons coupons = couponsMapper.queryById(entity);
        if (coupons == null) {
            return null;
        }
        Long couponsId = coupons.getId();
        //优惠券适用具体产品
        ProCoupons proCoupons = new ProCoupons();
        proCoupons.setCouponsId(couponsId);
        proCoupons.setPageFlag(false);
        List<ProCoupons> proCouponsList = proCouponsMapper.queryByExamplePage(proCoupons);
        coupons.setProCouponsList(proCouponsList);

        //优惠券下的品牌系列
        BrandSeries brandSeries = new BrandSeries();
        brandSeries.setCouponsId(couponsId);
        brandSeries.setPageFlag(false);
        List<BrandSeries> brandSeriesList = brandSeriesMapper.queryByExamplePage(brandSeries);
        coupons.setBrandSeriesList(brandSeriesList);
        return coupons;
    }

    /**
     * 编辑优惠卷
     * @author : wangdawei
     * @param couponsList 优惠券列表
     * @throws Exception 异常
     * @date : 2018/5/2
     */
    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public void updateCoupons(List<Coupons> couponsList) throws Exception {
        Coupons coup = new Coupons();
        if (!couponsList.isEmpty()) {
            coup.setActivityId(couponsList.get(0).getActivityId());
        } else {
            throw new ServiceException("COUPONS-005");
        }
        coup.setPageFlag(false);
        //找到活动下的所有旧的优惠券
        List<Coupons> oldCouponsList = couponsMapper.queryByExamplePage(coup);
        for (int i = 0; couponsList != null && i < couponsList.size(); i++) {
            Coupons coupons = couponsList.get(i);
            //编辑下的新建优惠券
            if ("NEW".equals(coupons.getRow_status())) {
                Long couponsId = coupons.getId();
                Long activityId = coupons.getActivityId();
                CoreUser user = UserUtil.getUser();
                //新建数据
                if (null == couponsId) {
                    couponsId = keyGenerateService.keyGenerate();
                    coupons.setId(couponsId);
                }
                coupons.setActivityId(activityId);
                coupons.setOrgId(user.getOrgId());
                coupons.setPostnId(user.getPostnId());
                if (StringUtils.isNotBlank(coupons.getCouponsClass()) && "Coupon".equals(coupons.getCouponsClass())) {
                    String str = PropertyUtil.getProperty("couponGetDirectlyURL",
                            user.getCorpid()) + "?id=" + couponsId + "&&corpid=" + user.getCorpid();
                    //二维码存放位置,静态路径。
                    String coupfile = "/web/file/saleactivity/" + user.getCorpid() + "/";
                    String name = couponsId + "_" + DateUtil.dateToStr(new Date(), "yyyyMMddHHmmss") + ".png";
                    //二维码的本地路径（默认Portal文件系统根目录）
                    QRCodeUtil.tomakeMode(str, YmlConstants.getPortalShareFileDir() + coupfile, name, 140, 140);
                    coupons.setCodeSavPath(coupfile + name);
                    coupons.setCodeUrl(str);
                }
                coupons.setActivityId(activityId);
                couponsMapper.insert(coupons);
                //保存活动下的具体适用产品信息
                List<ProCoupons> proCouponsList = couponsList.get(i).getProCouponsList();
                if (proCouponsList != null) {
                    for (int j = 0; j < proCouponsList.size(); j++) {
                        ProCoupons proCoupons = proCouponsList.get(j);
                        Long proCouponsId = proCoupons.getId();
                        if (null == proCouponsId) {
                            proCouponsId = keyGenerateService.keyGenerate();
                            proCoupons.setId(proCouponsId);
                        }
                        proCoupons.setCouponsId(couponsId);
                        proCouponsMapper.insert(proCoupons);
                    }
                }

                //保存活动下的品牌系列信息
                List<BrandSeries> brandSeriesbList = couponsList.get(i).getBrandSeriesList();
                if (brandSeriesbList != null) {
                    for (int j = 0; j < brandSeriesbList.size(); j++) {
                        BrandSeries brandSeries = brandSeriesbList.get(j);
                        Long brandSeriesId = brandSeries.getId();
                        if (null == brandSeriesId) {
                            brandSeriesId = keyGenerateService.keyGenerate();
                            brandSeries.setId(brandSeriesId);
                        }
                        brandSeries.setCouponsId(couponsId);
                        if (StringUtils.isNotBlank(brandSeries.getBrandseriesType())) {
                            brandSeriesMapper.insert(brandSeries);
                        }
                    }
                }
                //新建状态下的，优惠券同步到微信
                if (StringUtils.isNotBlank(coupons.getIsSyn())) {
                    if ("Y".equals(coupons.getIsSyn())) {
                        //调用优惠卷同步微信接口
                        Map<String, Object> map = articlesService.createWxCard(coupons);
                        Object cardId = map.get("card_id");
                        // card_id存在表示卡券同步微信成功
                        if (cardId != null && StringUtils.isNotBlank(cardId.toString())) {
                            coupons.setWeChatCouponId(cardId.toString());
                            coupons.setSynState("Succeeded");
                            coupons.setSynTime(DateUtil.dateToStr(new Date(), "yyyy-MM-dd HH:mm:ss"));
                            couponsMapper.update(coupons);
                        } else {
                            //同步失败，数据回滚。
                            throw new ServiceException("COUPONS-006");
                        }
                    }
                }
                //编辑优惠券
            } else if (null != coupons.getId() && "UPDATE".equals(coupons.getRow_status())) {
                Long couponsId = coupons.getId();
                if (null == couponsId) {
                    throw new ServiceException("COUPONS-016");
                }
                //查询旧的数据
                coupons.setId(couponsId);
                Coupons couponsOld = this.getCouponsById(coupons);
                if (couponsOld == null) {
                    throw new Exception("COUPONS-017");
                }
                //更新优惠券
                couponsMapper.update(coupons);
                /*编辑优惠券适用门店*/
                List<ProCoupons> proCouponsList = coupons.getProCouponsList();
                //本来数据库的信息
                List<ProCoupons> oldproCouponsList = couponsOld.getProCouponsList();
                for (int p = 0; proCouponsList != null && p < proCouponsList.size(); p++) {
                    ProCoupons proCoupons = proCouponsList.get(p);
                    Long proCouponsId = proCoupons.getId();
                    //新建数据
                    if ("NEW".equals(proCoupons.getRow_status())) {
                        if (null == proCouponsId) {
                            proCouponsId = keyGenerateService.keyGenerate();
                            proCoupons.setId(proCouponsId);
                        }
                        proCoupons.setCouponsId(couponsId);
                        proCouponsMapper.insert(proCoupons);
                        //更新数据
                    } else if ("UPDATE".equals(proCoupons.getRow_status())) {
                        if (null == proCouponsId) {
                            throw new ServiceException("COUPONS-008");
                        }
                        proCoupons.setCouponsId(couponsId);
                        proCouponsMapper.update(proCoupons);
                    }
                }
//        找出无用数据并删除
                for (int q = 0; oldproCouponsList != null && proCouponsList != null && q < oldproCouponsList.size(); q++) {
                    ProCoupons oldProCoupons = oldproCouponsList.get(q);
                    boolean delFlag = true;
                    for (int j = 0; oldproCouponsList != null && j < proCouponsList.size(); j++) {
                        if (oldProCoupons.getId().equals(proCouponsList.get(j).getId())) {
                            delFlag = false;
                            break;
                        }
                    }
                    //删除多余信息
                    if (delFlag) {
                        proCouponsMapper.deleteById(oldProCoupons);
                    }
                }
                /*编辑优惠券的产品系列*/
                List<BrandSeries> brandSeriesList = coupons.getBrandSeriesList();
                //本来数据库的信息
                List<BrandSeries> oldbrandSeriesList = couponsOld.getBrandSeriesList();
                for (int r = 0; brandSeriesList != null && r < brandSeriesList.size(); r++) {
                    BrandSeries brandSeries = brandSeriesList.get(r);
                    Long brandSeriesId = brandSeries.getId();
                    //新建数据
                    if ("NEW".equals(brandSeries.getRow_status())) {
                        if (null == brandSeriesId) {
                            brandSeriesId = keyGenerateService.keyGenerate();
                            brandSeries.setId(brandSeriesId);
                        }
                        brandSeries.setCouponsId(couponsId);
                        if (StringUtils.isNotBlank(brandSeries.getBrandseriesType())) {
                            brandSeriesMapper.insert(brandSeries);
                        }
                        //更新数据
                    } else if ("UPDATE".equals(brandSeries.getRow_status())) {
                        if (null == brandSeriesId) {
                            throw new ServiceException("COUPONS-009");
                        }
                        brandSeries.setCouponsId(couponsId);
                        brandSeriesMapper.update(brandSeries);
                    }
                }

                //找出无用数据并删除
                if (!oldbrandSeriesList.isEmpty() && brandSeriesList != null) {
                    for (int s = 0; oldbrandSeriesList != null && brandSeriesList != null && s < oldbrandSeriesList.size(); s++) {
                        BrandSeries oldbrandSeries = oldbrandSeriesList.get(s);
                        boolean delFlag = true;
                        for (int j = 0; oldbrandSeriesList != null && j < brandSeriesList.size(); j++) {
                            if (oldbrandSeries.getId().equals(brandSeriesList.get(j).getId())) {
                                delFlag = false;
                                break;
                            }
                        }
                        //删除活动
                        if (delFlag) {
                            brandSeriesMapper.deleteById(oldbrandSeries);
                        }
                    }
                }
            }
            //删除优惠券
            if (!oldCouponsList.isEmpty() && !couponsList.isEmpty()) {
                for (int s = 0; oldCouponsList != null && couponsList != null && s < oldCouponsList.size(); s++) {
                    Coupons oldCoupons = oldCouponsList.get(s);
                    boolean delFlag = true;
                    for (int j = 0; oldCouponsList != null && j < couponsList.size(); j++) {
                        //编辑下的优惠券同步到微信
                        if (oldCoupons.getId().equals(couponsList.get(j).getId())) {
                            if ("N".equals(oldCoupons.getIsSyn()) && "Y".equals(couponsList.get(j).getIsSyn())) {
                                Map<String, Object> map = articlesService.createWxCard(coupons);
                                Object cardId = map.get("card_id");
                                // card_id存在表示卡券同步微信成功
                                if (cardId != null && StringUtils.isNotBlank(cardId.toString())) {
                                    coupons.setWeChatCouponId(map.get("card_id").toString());
                                    coupons.setSynFeedback((String) map.get("errmsg"));
                                    coupons.setSynState("Succeeded");
                                    coupons.setSynTime(DateUtil.dateToStr(new Date(), "yyyy-MM-dd HH:mm:ss"));
                                    couponsMapper.update(coupons);
                                } else if (null == cardId) {
                                    //同步失败，数据回滚。
                                    if (map.get("card_id") != null) {
                                        coupons.setWeChatCouponId(map.get("card_id").toString());
                                    }
                                    coupons.setSynFeedback((String) map.get("errmsg"));
                                    coupons.setSynState("Failed");
                                    coupons.setSynTime(DateUtil.dateToStr(new Date(), "yyyy-MM-dd HH:mm:ss"));
                                    couponsMapper.update(coupons);
                                } else {
                                    throw new ServiceException("PUBLIC-034");
                                }
                            }
                            delFlag = false;
                            break;
                        }
                    }
                    //删除删除优惠券,并且删除优惠券下所有的关联数据
                    if (delFlag) {
                        if (null == oldCoupons.getId()) {
                            throw new Exception("COUPONS-004");
                        }

                        couponsMapper.deleteById(oldCoupons);
                        //删除优惠券下的品牌系列信息
                        List<BrandSeries> brandSeriesList = oldCoupons.getBrandSeriesList();
                        for (int h = 0; brandSeriesList != null && h < brandSeriesList.size(); h++) {
                            brandSeriesMapper.deleteById(brandSeriesList.get(h));
                        }

                        //删除优惠券的适用产品信息
                        List<ProCoupons> proCouponsList = oldCoupons.getProCouponsList();
                        for (int w = 0; proCouponsList != null && w < proCouponsList.size(); w++) {
                            proCouponsMapper.deleteById(proCouponsList.get(w));
                        }
                    }

                }
            }
        }
    }


    /**
     * <p>优惠券领取通用接口</p>
     * @author wangdawei
     * @param entity
     * @date 2018-5-16
     */
    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public void receiceCoupons(Coupons entity, CollectRecord collectRecord) throws Exception {
        //优惠券领取更新优惠券表内信息
        Coupons coupons = queryById(entity.getId());
        if (coupons.getReceivedNum() == null) {
            coupons.setUnclaimedNum(coupons.getCouponsNum());
        }
        coupons.setUnclaimedNum(coupons.getUnclaimedNum() - 1);
        coupons.setReceivedNum(coupons.getReceivedNum() + 1);
        String status = "ToBeReleased";
        if (status.equals(coupons.getCouponsStuts())) {
            coupons.setCouponsStuts("Distributed");
        }
        couponsMapper.update(coupons);
        //新建一条客户领取记录
        collectRecord.setClaimTime(DateUtil.dateToStr(new Date(), "yyyy-MM-dd"));
        collectRecord.setClaimStatus("Received");
        String fixedDate = "FixedDate";
        if (fixedDate.equals(entity.getValidityOption())) {
            collectRecord.setEffectStaTime(coupons.getEffectStaTime());
            collectRecord.setEffectEndTime(coupons.getEffectEndTime());
        } else {
            collectRecord.setEffectStaTime(DateUtil.dateToStr(new Date(), "yyyy-MM-dd"));
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            Date d = new Date();
            collectRecord.setEffectEndTime(df.format(new Date(d.getTime() + (long) coupons.getEffetDay() * 24 * 60 * 60 * 1000)));
        }
        if (collectRecord.getId() == null) {
            collectRecord.setId(keyGenerateService.keyGenerate());
        }
        collectRecordService.insert(collectRecord);
    }


    /**
     * 使用优惠卷(核销优惠券)
     * @author : wangdawei
     * @param entity 优惠券领取记录对象
     * @return map
     * @throws Exception
     * @date : 2018/5/16
     */
    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public Map<String, Object> useCoupons(CollectRecord entity) throws Exception {
        //核销优惠卷，获取一个默认登录用户
        // 获取一个默认登录用户

        User user = userService.queryUserByCropId(entity.getCorpid());
        SecurityInterceptor.tempUser.set(user);
        List<CollectRecord> collectRecordList = new ArrayList<>();
        CollectRecord collectRecord = new CollectRecord();
        Coupons coupons = new Coupons();
        //通过微信领取，前端传入客户id，优惠券id
        if (null == entity.getAccntId() && null == entity.getCouponsId()
                && null != entity.getWechatCode()) {
            collectRecord.setWechatCode(entity.getWechatCode());
            collectRecord.setPageFlag(false);
            collectRecordList = collectRecordService.queryByExamplePage(collectRecord);
            CollectRecord collectRe = collectRecordList.get(0);
            String wxId = collectRe.getWechatId();
            String code = collectRe.getWechatCode();
            Map<String, Object> map = new HashMap<>(16);
            //865903682697
            map.put("code", code);
            WxPlatform wxPlatform = new WxPlatform();
            wxPlatform.setId(Long.parseLong(wxId));
            WxPlatform platform = wxPlatformService.queryById(wxPlatform);
            String accessToken;
            accessToken = wxTokenService.getWxAccessTokenByAppId(platform.getWx_app_id()).getAccess_token();
            String requestUrl = env.getProperty("weixinuri.destroyCodeUrl").replace("ACCESS_TOKEN", accessToken);
            // 转换成特定格式字符串，领取信息同步微信
            String data = JsonUtil.toString(map);
            JSONObject res = WeixinHttpUtil.httpRequest(requestUrl, "POST", data);
            String zero = "0";
            String errcode = "errcode";
            if (zero.equals(res.get(errcode).toString())) {
                for (int i = 0; i < collectRecordList.size(); i++) {
                    collectRecordList.get(i).setClaimStatus("Used");
                    collectRecordList.get(0).setUseTime(DateUtil.dateToStr(new Date(), "yyyy-MM-dd"));
                    collectRecordList.get(0).setUseChannel("MP");
                    collectRecordList.get(i).setAnonymousFlag("Y");
                    collectRecordList.get(i).setPostnId(user.getPostnId());
                    collectRecordService.update(collectRecordList.get(i));
                }
            }
            map.put("result", res);
            //通过lnk渠道领取
        } else {
            collectRecord.setPageFlag(false);
            collectRecord.setCouponsId(entity.getCouponsId());
            collectRecord.setAccntId(entity.getAccntId());
            collectRecordList = collectRecordService.queryByExamplePage(collectRecord);
        }
        Coupons coup = new Coupons();
        if (null != entity.getCouponsId()) {
            coup.setId(entity.getCouponsId());
            coupons = couponsMapper.queryById(coup);
        }
        if (coupons.getUsedNum() == null) {
            coupons.setUsedNum(0);
        }
        coupons.setUsedNum(coupons.getUsedNum() + 1);
        String stuts = "ToBeReleased";
        if (stuts.equals(entity.getCouponsStuts())) {
            //优惠卷状态设置为已投放
            entity.setCouponsStuts("Distributed");
        }
        coupons.setAnonymousFlag("Y");
        coupons.setPostnId(user.getPostnId());
        couponsMapper.update(coupons);
        collectRecord.setAccntId(coupons.getAccntId());
        collectRecord.setCouponsId(coupons.getId());
        collectRecord.setClaimStatus("Received");
        collectRecord.setPageFlag(false);
        collectRecordList = collectRecordService.queryByExamplePage(collectRecord);
        if (collectRecordList != null && collectRecordList.size() != 0) {
            collectRecordList.get(0).setClaimStatus("Used");
            if (null != coupons.getUserPeopleId()) {
                collectRecordList.get(0).setUserId(coupons.getUserPeopleId());
            }
            if (null != coupons.getUseStoreId()) {
                //添加优惠券使用门店
                collectRecordList.get(0).setUseStoreId(coupons.getUseStoreId());
            }
            collectRecordList.get(0).setUseTime(DateUtil.dateToStr(new Date(), "yyyy-MM-dd"));
            collectRecordList.get(0).setAnonymousFlag("Y");
            collectRecordList.get(0).setPostnId(user.getPostnId());
            collectRecordList.get(0).setUseChannel("MP");
            collectRecordService.update(collectRecordList.get(0));
        }
        Map<String, Object> result = new HashMap<String, Object>(4);
        result.put("success", true);
        return result;
    }

    /**
     * 删除活动下的优惠券，以及品牌系列，优惠券的使用产品信息
     * @author : wangdawei
     * @param entity 优惠券对象
     * @throws Exception
     * @date : 2018/5/16
     */
    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public void deleteCoupons(Coupons entity) throws Exception {

        if (null == entity.getId()) {
            throw new ServiceException("COUPONS-004");
        }

        //删除优惠券表信息
        couponsMapper.deleteById(entity);

        //删除优惠券下的品牌系列信息
        List<BrandSeries> brandSeriesList = entity.getBrandSeriesList();
        for (int i = 0; brandSeriesList != null && i < brandSeriesList.size(); i++) {
            brandSeriesMapper.deleteById(brandSeriesList.get(i));
        }

        //删除优惠券的适用产品信息
        List<ProCoupons> proCouponsList = entity.getProCouponsList();
        for (int i = 0; proCouponsList != null && i < proCouponsList.size(); i++) {
            proCouponsMapper.deleteById(proCouponsList.get(i));
        }
    }

    /**
     * pc端查看优惠券信息
     * @author : wangdawei
     * @param entity 优惠券对象
     * @return 领取记录列表
     * @throws Exception
     * @date : 2018/5/16
     */
    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public List<CollectRecord> pcGetCoupons(Coupons entity) throws Exception {
        List<Account> accountList = new ArrayList<>();
        CoreUser user = UserUtil.getUser();
        if (null == user) {
            user = userService.queryUserByCropId(entity.getCorpid());
            SecurityInterceptor.tempUser.set(user);
        }
        List<CollectRecord> list = new ArrayList<>();
        Account acct1 = new Account();
        acct1.setId(entity.getAccntId());
        acct1 = accountService.queryById(acct1);
        acct1.setAttr1("mobilePhone");
        accountList = accountService.queryAcctListById(acct1);
        for (int i = 0; i < accountList.size(); i++) {
            CollectRecord collectRecord = new CollectRecord();
            collectRecord.setPageFlag(false);
            collectRecord.setCouponsClass(entity.getCouponsClass());
            collectRecord.setClaimStatus(entity.getClaimStatus());
            collectRecord.setAccntId(accountList.get(i).getId());
            List<CollectRecord> collectRecordList = collectRecordMapper.queryByExamplePage(collectRecord);
            for (int j = 0; collectRecordList != null && j < collectRecordList.size(); j++) {
                list.add(collectRecordList.get(j));
            }
        }
        return list;
    }

    /**
     * 展示优惠券
     * @author : wangdawei
     * @param entity 优惠券对象
     * @return list优惠券列表
     * @throws Exception
     * @date : 2018/5/16
     */
    @Override
    public List<Coupons> showCoupons(Coupons entity) throws Exception {
        // 获取一个默认登录用户
        User user = userService.queryUserByCropId(entity.getCorpid());
        SecurityInterceptor.tempUser.set(user);
        if (null == entity.getActivityId()) {
            throw new ServiceException("COUPONS-010");
        }
        Account account = new Account();
        CollectRecord collectRecord = new CollectRecord();
        Coupons coupon = new Coupons();
        coupon.setActivityId(entity.getActivityId());
        coupon.setPageFlag(false);
        //产看活动下的优惠卷
        List<Coupons> couponsList = couponsMapper.queryByExamplePage(coupon);
        if (StringUtils.isNotBlank(entity.getMobilePhone())) {
            account.setMobilePhone1(entity.getMobilePhone());
            account.setPageFlag(false);
            account.setCorpid(user.getCorpid());
            account.setLoginCorpId(user.getCorpid());
            //根据客户电话号码匹配客户
            List<Account> accountList = accountService.queryByExamplePage(account);
            for (int i = 0; couponsList != null && i < couponsList.size(); i++) {
                for (int j = 0; accountList != null && j < accountList.size(); j++) {
                    collectRecord.setCouponsId(couponsList.get(i).getId());
                    collectRecord.setAccntId(accountList.get(j).getId());
                    collectRecord.setPageFlag(false);
                    //根据客户id，和优惠卷id，查出客户已领取的优惠卷
                    List<CollectRecord> collectRecordList = collectRecordService.queryByExamplePage(collectRecord);
                    if (collectRecordList.size() != 0) {
                        // 已领取
                        couponsList.get(i).setClaimStatus("Received");
                        couponsList.get(i).setAnonymousFlag("Y");
                        break;
                    }

                }
            }
        }
        for (int i = 0; couponsList.size() != 0 && i < couponsList.size(); i++) {
            if ("Y".equals(couponsList.get(i).getIsEffect())) {
                CollectRecord record = new CollectRecord();
                record.setCouponsId(couponsList.get(i).getId());
                record.setPageFlag(false);
                //根据客户id，和优惠卷id，查出客户已领取的优惠卷
                List<CollectRecord> recordList = collectRecordService.queryByExamplePage(record);
                if (couponsList.get(i).getReceivedNum() == null) {
                    couponsList.get(i).setReceivedNum(0);
                }
                Boolean flag = couponsList.get(i).getReceivedNum() < couponsList.get(i).getCouponsNum();
                if (StringUtils.isBlank(couponsList.get(i).getClaimStatus())) {
                    if (flag) {
                        // 可领取
                        couponsList.get(i).setClaimStatus("New");
                    } else {
                        // 已领完
                        couponsList.get(i).setClaimStatus("BroughtUp");
                    }
                }
                couponsList.get(i).setAnonymousFlag("Y");

            } else {
                // 已过期
                couponsList.get(i).setClaimStatus("Expired");
            }

            couponsList.get(i).setAnonymousFlag("Y");
        }
        return couponsList;
    }

    /**
     * 根据客户id查询客户下的奖品列表
     * @author : LiQun
     * @param present 礼品对象
     * @return 产品列表
     * @throws Exception 异常
     * @date : 下午7:13 2018/5/2
     */
    @Override
    public List<Present> queryPresentsByAccountId(Present present) throws Exception {
        return couponsMapper.queryPresentsByAccountId(present);
    }

    /**
     * 根据id更新礼品状态,将其置为已使用
     * @author : LiQun
     * @param present 礼品对象
     * @throws Exception 异常
     * @date : 下午7:15 2018/5/2
     */
    @Override
    public void presentStatusUpdate(Present present) throws Exception {
        couponsMapper.presentStatusUpdate(present);
    }

    /**
     * 会员卡查询
     * @author lujiang
     * @param coupons
     * @return map
     * @throws Exception
     * @throws Exception
     * 10/9 2018
     */
    @Override
    public Map<String, Object> queryWxCard(Coupons coupons) throws Exception {
        Map<String, Object> result = new HashMap<>(4);
        Map<String, Object> map = new HashMap<>(16);
        //设置查询参数
        map.put("offset", 0);
        map.put("count", 50);
        List<String> list = new ArrayList<>();
        list.add("CARD_STATUS_DELETE");
        map.put("status_list", list);
        //将map 转换为json
        String data = JsonUtil.toString(map);
        //获取微信公众号信息，目的是获取token
        WxPlatform wxPlatform = new WxPlatform();
        wxPlatform.setId(coupons.getWeChatId());
        WxPlatform platform = wxPlatformService.queryById(wxPlatform);
        //获取token工具类
        String accessToken = wxTokenService.getWxAccessTokenByAppId(platform.getWx_app_id()).getAccess_token();
        String requestUrl = env.getProperty("weixinuri.queryCardListUrl").replace("TOKEN", accessToken);
        //http 请求
        JSONObject json = WeixinHttpUtil.httpRequest(requestUrl, "POST", data);
        List<String> cardIdList = new ArrayList<>();
        String zero = "0";
        String errcode = "errcode";
        //得到会员卡id 遍历详情
        if (zero.equals(json.get(errcode).toString())) {
            String cardList = json.get("card_id_list").toString();
            String[] strs = cardList.split(",");
            for (int i = 0, len = strs.length; i < len; i++) {
                cardIdList.add(strs[i]);
            }
            List<Object> jsonObjectList = new ArrayList<>();
            for (int j = 0; j < cardIdList.size(); j++) {
                Map<String, Object> datamap = new HashMap<>(16);
                datamap.put("card_id", cardIdList.get(j));
                String url = env.getProperty("weixinuri.queryCardUrl").replace("TOKEN", accessToken);
                String jsondata = JsonUtil.toString(datamap);
                JSONObject jsonObject = WeixinHttpUtil.httpRequest(url, "POST", jsondata);
                jsonObjectList.add(jsonObject);
            }
            result.put("success", true);
            result.put("rows", jsonObjectList);
        } else {
            result.put("success", false);
        }
        return result;
    }

    /**
     * 小程序领取优惠券s
     * @author lujiang
     * @param couponss
     * @param openId   微信openId
     * @return map
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public Map<String, Object> getWxCard(List<Coupons> couponss, String openId) throws Exception {
        Map<String, Object> map = new HashMap<>(4);
        //查询客户信息
        Account account = new Account();
       // account.setWxOwnOpenId(openId);
        account.setPageFlag(false);
        List<Account> accountList = accountService.queryByExamplePage(account);
        if (accountList.size() < 1) {
            throw new ServiceException("COUPONS-011");
        } else {
            account = accountList.get(0);
        }
        //查询优惠券信息
        for (int i = 0; i < couponss.size(); i++) {
            Coupons coupons = couponsMapper.queryById(couponss.get(i));
            if (!("Y").equals(coupons.getIsEffect())) {
                map.put("msg", "优惠券无效");
                return map;
            }
            CollectRecord collectRecord = new CollectRecord();
            collectRecord.setReceiveChannel("Link");
            collectRecord.setClaimStatus("Received");
            collectRecord.setCouponsId(coupons.getId());
            collectRecord.setAccntId(account.getId());
            collectRecord.setCorpid(coupons.getCorpid());
            collectRecord.setClaimantNum(1);
            collectRecord.setClaimTime(DateUtil.dateToStr(new Date(), "yyyy-MM-dd HH:mm:ss"));
            if (StringUtils.isNotBlank(coupons.getValidityOption()) && "FixedTerm".equals(coupons.getValidityOption())) {
                collectRecord.setEffectStaTime(DateUtil.dateToStr(new Date(), "yyyy-MM-dd"));
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                Date d = new Date();
                if (null == coupons.getEffetDay()) {
                    coupons.setEffetDay(0);
                }
                collectRecord.setEffectEndTime(df.format(new Date(d.getTime() + (long) coupons.getEffetDay() * 24 * 60 * 60 * 1000)));
            } else {
                collectRecord.setEffectStaTime(coupons.getEffectStaTime());
                collectRecord.setEffectEndTime(coupons.getEffectEndTime());
            }
            //插入领取详情
            collectRecord.setAnonymousFlag("Y");
            collectRecord.setWechatCode(couponss.get(i).getCode());
            collectRecordService.insert(collectRecord);
        }
        map.put("success", true);
        return map;
    }

    /**
     * 根据产品查询优惠券
     * @author lujiang
     * @param product 产品对象
     * @return map
     * @throws Exception
     */
    @Override
    public Map<String, Object> productForCard(Product product) throws Exception {
        Map<String, Object> map = new HashMap<>(4);
        List<Coupons> list = new ArrayList<>();
        Coupons coupons = new Coupons();
        //优惠券状态目前先写为新建
        coupons.setCouponsStuts("ToBeReleased");
        coupons.setPageFlag(false);
        coupons.setAccntId(product.getAccntId());
        coupons.setAttr1("effective");
        coupons.setAttr3("Y");
        coupons.setLoginCorpId(product.getCorpid());
        List<Coupons> couponsList = this.queryByExamplePage(coupons);
        list = prodCoupons(product, couponsList);
        map.put("rows", list);
        return map;
    }

    /**
     * 取适合产品的优惠券
     * @author yipeng.zhu@hand-china.com
     * @param product     产品
     * @param couponsList 客户领取的优惠券集合
     * @return list 适合产品的优惠券集合
     * @date 2019/4/16 10:36
     */
    public List<Coupons> prodCoupons(Product product, List<Coupons> couponsList) throws Exception {
        List<Coupons> list = new ArrayList<>();
        //查询出新建的优惠券
        for (int i = 0; i < couponsList.size(); i++) {
            Coupons coup = couponsList.get(i);
            coup.setAnonymousFlag("Y");
            //优惠券匹配规则：匹配全部，所以优惠券都适用
            if ("All".equals(coup.getFitProd())) {
                list.add(coup);
                //具体产品，具体产品适用
            } else if ("Specified".equals(coup.getFitProd())) {
                ProCoupons proCoupons = new ProCoupons();
                proCoupons.setProdId(product.getId());
                proCoupons.setCouponsId(coup.getId());
                proCoupons.setPageFlag(false);
                proCoupons.setLoginCorpId(product.getCorpid());
                List<ProCoupons> proCouponsList = proCouponsMapper.queryByExamplePage(proCoupons);
                if (proCouponsList.size() > 0) {
                    list.add(coup);
                }
                //品牌系列适用
            } else if ("BrandSeries".equals(coup.getFitProd())) {
                // 产品是否有品牌
                boolean flagBrand = (null == product.getProdBrand() || ("").equals(product.getProdBrand())) ? true : false;
                //产品是否有系列
                boolean flagSeries = (("").equals(product.getProdMatSeries()) || null == product.getProdMatSeries()) ? true : false;
                // 如果产品没有品牌系列就结束
                if (flagBrand && flagSeries) {
                    continue;
                }
                BrandSeries brandSeries = new BrandSeries();
                brandSeries.setCouponsId(coup.getId());
                brandSeries.setPageFlag(false);
                brandSeries.setLoginCorpId(product.getCorpid());
                List<BrandSeries> brandSeriesList = brandSeriesMapper.queryByExamplePage(brandSeries);
                //查询优惠券下所有品牌系列配置
                Boolean brand = true;
                Boolean series = true;
                for (int j = 0; j < brandSeriesList.size(); j++) {
                    BrandSeries bS = brandSeriesList.get(j);
                    //品牌类型
                    if (bS != null && "Brand".equals(bS.getBrandseriesType())) {
                        //如果第一级品牌相等，往下判断
                        if (StringUtils.equals(bS.getProdFirstBrand(), product.getProdBrand())) {
                            brand = true;
                        } else {
                            brand = false;
                            break;
                        }
                        //二级品牌不为空，判断二级品牌是否相等，true 往下判断
                        if (StringUtils.isBlank(bS.getProdSecBrand()) || bS.getProdSecBrand().equals(product.getProdSecBrand())) {
                            brand = true;
                        } else {
                            brand = false;
                        }
                        //第三级品牌，如果三级都相等或者产品品牌归属配置品牌，true
                        if (brand) {
                            if (StringUtils.isBlank(bS.getProdThirdBrand()) || bS.getProdThirdBrand().equals(product.getProdThirdBrand())) {
                                brand = true;
                            } else {
                                brand = false;
                            }
                        }
                        //系列,逻辑如上
                    } else if (bS != null && "Series".equals(bS.getBrandseriesType())) {
                        if (StringUtils.equals(bS.getProdFirstSeries(), product.getProdMatSeries())) {
                            series = true;
                        } else {
                            series = false;
                            break;
                        }
                        if (StringUtils.isBlank(bS.getProdSecSeries()) || bS.getProdSecSeries().equals(product.getProdSecSeries())) {
                            series = true;
                        } else {
                            series = false;
                        }
                        if (series) {
                            if (StringUtils.isBlank(bS.getPeodThirdSeries()) || bS.getPeodThirdSeries().equals(product.getProdThirdSeries())) {
                                series = true;
                            } else {
                                series = false;
                            }
                        }
                    }
                }
                //当产品属性与优惠券下所有配置都匹配，add
                if (brand && series) {
                    list.add(coup);
                }
            }
        }
        // 排序
        Collections.sort(list, new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                Coupons stu1 = (Coupons) o1;
                Coupons stu2 = (Coupons) o2;
                return stu1.getDisAmount().compareTo(stu2.getDisAmount());
            }
        });
        return list;
    }

    /**
     * 小程序订单查询适用优惠券查询传入订单id,后台查询其余信息
     *
     * @param entity
     */
    @Override
    public void getMPAppOrderInfo(AppOrderInfo entity) throws Exception {
        SaleOrder saleOrder = new SaleOrder();
        saleOrder.setId(entity.getId());
        saleOrder = saleOrderService.queryById(saleOrder);
        if (null == saleOrder) {
            throw new ServiceException("COUPONS-012");
        }
        entity.setAccntId(saleOrder.getAcctId());
        //查询客户手机号
        Account account = new Account();
        account.setId(saleOrder.getAcctId());
        account = accountService.queryById(account);
        if (null == account) {
            throw new Exception("COUPONS-013");
        }
        entity.setPhoneNum(account.getMobilePhone());

        SaleOrderItem saleOrderItem = new SaleOrderItem();
        saleOrderItem.setHeadId(entity.getId());
        saleOrderItem.setPageFlag(false);
        List<SaleOrderItem> saleOrderItems = saleOrderItemService.queryByExamplePage(saleOrderItem);
        List<Product> productList = new ArrayList<>();
        for (int i = 0; i < saleOrderItems.size(); i++) {
            Product product = new Product();
            product.setId(saleOrderItems.get(i).getProdId());
            product = productMapper.queryById(product);
            productList.add(product);
        }
        entity.setProductList(productList);
    }

    /**
     * 根据订单信息查询优惠券
     * @author lujiang
     * @param entity
     * @return map
     * @throws Exception
     */
    @Override
    public Map<String, Object> queryOrderCoupons(AppOrderInfo entity) throws Exception {
        Map<String, Object> map = new HashMap<>(4);
        Coupons coupons = new Coupons();
        Account account = new Account();
        //同一个手机号下 不同客户id
        List<Long> acctIdList = null;
        //如果订单客户有手机号，则优惠券对应的客户的手机号与订单客户的手机号相同
        //如果订单客户没有手机号，则优惠券对应的客户ID与订单客户的客户ID相同
        if (null == entity.getPhoneNum() || "".equals(entity.getPhoneNum())) {
            coupons.setAccntId(entity.getAccntId());
        } else {
            account.setMobilePhone1(entity.getPhoneNum());
            account.setPageFlag(false);
            List<Account> accountList = accountMapper.queryByExamplePage(account);
            if (accountList.size() > 0) {
                acctIdList = new ArrayList<>(16);
                for (Account bean : accountList) {
                    acctIdList.add(bean.getId());
                }
                coupons.setAcctIdList(acctIdList);
            }
        }
        //设置分页
        coupons.setPage(entity.getPage());
        coupons.setPageFlag(true);
        coupons.setRows(entity.getRows());
        //当前时间在优惠券有效日期之内,是否有效
        coupons.setIsEffect("Y");
        coupons.setAttr3("Y");
        //用于筛选失效的券
        coupons.setAttr1("effective");
        //查询同一个手机号下包含多个消费者领取的优惠券，当前时间在优惠券有效时间内
        List<Coupons> couponsList = this.queryByExamplePage(coupons);
        //产品适用的优惠券
        List<Coupons> coulist = coupMatchProds(entity.getProductList(), couponsList);
        // 排序
        sortCoupons(coulist);
        // 导购助手不可用优惠券展示列表
        String strN = "N";
        // String received = "Received";
        if (strN.equals(entity.getCoupStuts())) {
            // List<String> reduce1 = list1.stream().filter(item -> !list2.contains(item)).collect(toList());
            List<Coupons> noList = couponsList.stream().filter(item -> !coulist.contains(item)).collect(Collectors.toList());
            coupons.setAttr3("N");
            List<Coupons> overTimeList = this.queryByExamplePage(coupons);
            if (overTimeList.size() > 0) {
                noList.addAll(overTimeList);
            }
            map.put("rows", noList);
            return map;
        }
        map.put("rows", coulist);
        return map;
    }

    /**
     * 每个产品适用的优惠券
     * @author yipeng.zhu@hand-china.com
     * @param productList 产品列表
     * @param couponsList  优惠券列表
     * @return distinctList  适合产品的优惠券列表
     * @throws
     * @date 2019/4/16 11:21
     */
    public List<Coupons> coupMatchProds(List<Product> productList, List<Coupons> couponsList) throws Exception {
        List<Coupons> coulist = new ArrayList<>();
        // map中key设置为优惠券id，value存储的是适用这个优惠券的所有产品金额之和
        Map<Long,Object> couponsPriceMap = new HashMap<>();
        //产品
        for (int i = 0; i < productList.size(); i++) {
            Product product = productList.get(i);
            //产品的优惠券
            List<Coupons> list = prodCoupons(product, couponsList);
            for (int k = 0; k < list.size(); k++) {

                //产品促销价计入优惠券
                Coupons coup = couponsList.get(k);
                //订单产品购买数量
                int num = 0;
                if (StringUtils.isNotBlank(product.getAttr2())) {
                    num = Integer.parseInt(product.getAttr2());
                }
                // 如果map中未存储该优惠券，则put,如果存在金额累加
                if (null == couponsPriceMap.get(coup.getId())) {
                    couponsPriceMap.put(coup.getId(),product.getSalePrice() * num);
                } else {
                    Double price = product.getSalePrice() * num
                            + Double.valueOf(couponsPriceMap.get(coup.getId()).toString());
                    couponsPriceMap.put(coup.getId(),price);
                }
            }
        }
        // 在此客户已领取的券中找出适用订单下产品适用的优惠券，
        // 并将该优惠券实际减免金额赋值到attr1中，用作排序
        for (Coupons coupons : couponsList) {
            Iterator keys = couponsPriceMap.keySet().iterator();
            while (keys.hasNext()) {
                Long key = (Long)keys.next();
                Double price = Double.valueOf(couponsPriceMap.get(key).toString());
                if (key.equals(coupons.getId()) && coupons.getAmountLimit() <= price) {
                    coupons.setAttr1(price.toString());
                    coulist.add(coupons);
                }
            }
        }
        // 实际减免金额与优惠金额作比较，取较小值，用作排序
        for (Coupons coupon: coulist) {
            if (coupon.getDisAmount() < Double.valueOf(coupon.getAttr1())) {
                coupon.setAttr1(coupon.getDisAmount().toString());
            }
        }
        List<Coupons> distinctList = coulist.stream().distinct().collect(Collectors.toList());
        return distinctList;
    }

    /**
     * 优惠券实际减免金额赋值排序
     * @author yipeng.zhu@hand-china.com
     * @param list
     * @return
     * @throws
     * @date 2019/4/15 20:16
     */
    public void sortCoupons(List<Coupons> list) {
        // 排序
        Collections.sort(list, new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                Coupons stu1 = (Coupons) o1;
                Coupons stu2 = (Coupons) o2;
                return Double.valueOf(stu2.getAttr1()).compareTo(Double.valueOf(stu1.getAttr1()));
            }
        });
    }

    /*
     * 扫码核销优惠券
     * @author  wangdawei
     * @param entity
     * @return
     * @throws Exception
     */
    @Override
    public Coupons scanCodeUseCoup(Coupons entity) throws Exception {
        String strJson = "";
        //二维码内容,优惠券id ，客户id
        strJson = entity.getId() + "," + entity.getAccntId();
        //二维码存放位置,静态路径。
        String file = "/web/file/saleactivity/" + entity.getCorpid() + "/";
        String fileName = entity.getId() + "_" + DateUtil.dateToStr(new Date(), "yyyyMMddHHmmss") + ".png";
        //二维码的本地路径（默认Portal文件系统根目录）
        QRCodeUtil.tomakeMode(strJson, YmlConstants.getPortalShareFileDir() + file, fileName, 200, 200);
        entity.setCodeSavPath(YmlConstants.getPortalShareUrlDir() + file + fileName);
        entity.setCodeUrl(strJson);
        return entity;
    }

    /**
     * 累加领取红包的数量
     *
     * @param coupons 优惠券
     * @return 返回更新的记录条数
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public int updateReceivedNum(Coupons coupons) throws Exception {
        return couponsMapper.updateReceivedNum(coupons);
    }

    /**
     * 领取优惠券创建客户逻辑
     * @author wangdawei
     * @param entity
     * @return
     * @throws Exception
     */
    @Transactional(rollbackFor = ServiceException.class)
    public Account getAccnt(Coupons entity, String openId, CoreUser user) throws Exception {
        List<Account> accountList = new ArrayList<>();
        Account account = new Account();
        account.setMobilePhone1(entity.getMobilePhone());
        account.setPageFlag(false);
        account.setLoginCorpId(entity.getLoginCorpId());
        account.setCorpid(entity.getCorpid());
        accountList = accountService.queryByExamplePage(account);
        int total = -1;
        //H5 领券逻辑
        //客户来源为门店客户
        String store = "Store";
        //客户来源为活动客户
        String campaign = "Campaign";
        //Attr1 用来标识客户导购助手app客户来源，导购助手app必传字段
        if (!store.equals(entity.getAttr1())) {
            for (int i = 0; i < accountList.size(); i++) {
                if (StringUtils.isNotBlank(accountList.get(i).getAcctChannel())) {
                    if (campaign.equals(accountList.get(i).getAcctChannel())) {
                        total = i;
                        break;
                    }
                }
            }
        } else {
            //导购助手app 逻辑
            for (int i = 0; i < accountList.size(); i++) {
                if (StringUtils.isNotBlank(accountList.get(i).getAcctChannel())) {
                    if (store.equals(accountList.get(i).getAcctChannel())) {
                        total = i;
                        break;
                    }
                }
            }
        }
        if (total > -1) {
            //客户存在，更新微信的微信openId一条客户领券记录
            account = accountList.get(total);
            if (StringUtils.isNotBlank(openId)) {
                account.setPostnId(user.getPostnId());
                account.setLastUpdatedBy(user.getId());
                accountService.update(account);
            }
            //校验该活动客户是否已经领过优惠券
            this.checkCoupons(account, entity);
        } else {
            //客户不存在则创建客户，并把优惠券领取到该用户。
            account.setMobilePhone1(entity.getMobilePhone());
            account.setAcctType("ChannelConsumer");
            // 导购id不为空，把导购的组织id赋给新建客户的orgId
            if (null != entity.getGuideId()) {
                User u = new User();
                u.setId(entity.getGuideId());
                u = userService.queryById(u);
                account.setOrgId(u.getDeptId());
            }
            if (!store.equals(entity.getAttr1())) {
                account.setAcctName("活动客户" + entity.getMobilePhone().substring(7, 11));
                account.setAcctChannel("Campaign");
            } else {
                account.setAcctName("门店客户" + entity.getMobilePhone().substring(7, 11));
                account.setAcctChannel("Store");
            }
            account.setAcctStatus("Y");
            account.setAcctLevel("A");
            account.setIsOldCustomer("N");
            account.setAcctStage("PotentialConsumer");
            account.setCorpid(entity.getCorpid());
            account.setLoginCorpId(entity.getCorpid());
            account.setAnonymousFlag("Y");
            account.setPostnId(user.getPostnId());
            accountService.insert(account);
        }
        return account;
    }

    /**
     * 存放信息放入redis
     *
     * @param coupons 优惠券
     * @return 返回更新的记录条数
     * @throws Exception
     */
    public void putInfoResdis(Coupons coupons, Account account) throws Exception {
        String redisKey = coupons.getId() + VCODECACHE_KEYSUFFIX;
        LinkRedisClient jedis = null;
        try {
            jedis = RedisUtil.getJedis();
            jedis.set(redisKey, account.getAcctChannel());
            //一分钟内有效
            jedis.expire(redisKey, VCODE_EFFECTIVETIME);
        } finally {
            RedisUtil.returnResource(jedis);
        }
    }

    /**
     * H5领取多张优惠券
     *
     * @param couponsList 优惠券列表
     * @return couponsList
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public Map<String, Object> receiveCoupons(List<Coupons> couponsList, String mobilePhone, String openId, Long corpid) throws Exception {
        Map<String, Object> map = new HashMap<>(8);
        if (couponsList.isEmpty()) {
            throw new ServiceException("COUPONS-014");
        }
        //无状态登录获取用户信息，默认获取管理员信息
        User user = userService.queryUserByCropId(corpid);
        SecurityInterceptor.tempUser.set(user);
        // 获取领券客户
        Coupons coupons = couponsList.get(0);
        coupons.setMobilePhone(mobilePhone);
        //获取领券客户
        Account acct = this.getAccnt(coupons, openId, user);
        for (Coupons entity : couponsList) {
            // 只领取有效的优惠券,并且没有同步到微信券
            if ("Y".equals(entity.getIsEffect())) {
                //领券记录
                CollectRecord collectRecord = new CollectRecord();
                //来源导购id
                if (null != entity.getGuideId()) {
                    collectRecord.setSourceGuideId(entity.getGuideId());
                }
                collectRecord.setCorpid(entity.getCorpid());
                collectRecord.setCouponsId(entity.getId());
                collectRecord.setAccntId(acct.getId());
                collectRecord.setClaimantNum(1);
                collectRecord.setClaimTime(DateUtil.dateToStr(new Date(), "yyyy-MM-dd HH:mm:ss"));
                collectRecord.setReceiveChannel("Link");
                if ("N".equals(entity.getIsSyn())) {
                    collectRecord.setClaimStatus("Received");
                } else {
                    Long id = keyGenerateService.keyGenerate();
                    collectRecord.setId(id);
                    collectRecord.setClaimStatus("New");
                    collectRecord.setWechatCode(id.toString());
                }
                collectRecord.setPostnId(user.getPostnId());
                if (null != entity.getIssueSroreId()) {
                    //添加发放门店
                    collectRecord.setIssueSroreId(entity.getIssueSroreId());
                }
                String fixedTerm = "FixedTerm";
                if (StringUtils.isNotBlank(coupons.getValidityOption()) && fixedTerm.equals(coupons.getValidityOption())) {
                    collectRecord.setEffectStaTime(DateUtil.dateToStr(new Date(), "yyyy-MM-dd"));
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                    Date d = new Date();
                    if (coupons.getEffetDay() == null) {
                        coupons.setEffetDay(0);
                    }
                    collectRecord.setEffectEndTime(df.format(new Date(d.getTime() + (long) coupons.getEffetDay() * 24 * 60 * 60 * 1000)));
                } else {
                    collectRecord.setEffectStaTime(coupons.getEffectStaTime());
                    collectRecord.setEffectEndTime(coupons.getEffectEndTime());
                }
                //插入领取详情
                collectRecord.setAnonymousFlag("Y");
                collectRecordService.insert(collectRecord);
                if (coupons.getReceivedNum() == null) {
                    coupons.setReceivedNum(0);
                }
                coupons.setReceivedNum(coupons.getReceivedNum() + 1);
                coupons.setAnonymousFlag("Y");
                update(coupons);
                entity.setClaimStatus("Received");
            }
        }
        /************非微信渠道领取优惠券成功之后，自动调用短信接口发送短信通知客户，短信接口,发送短信***********/
        String prizeType = coupons.getCouponsClass();
        pushSmsService.pullDiscountCouponSendSms(prizeType, acct.getId(),
                coupons.getCouponsName(), acct.getId() + "&&corpid=" + user.getCorpid(), user.getCorpid());
        map.put("rows", couponsList);
        return map;
    }

    /**
     * 查询小程序订单可用优惠券
     * @author KuangRuifeng
     * @param entity 订单信息
     * @return 优惠券列表
     * @throws Exception 异常信息
     * @date 2018年12月6日
     */
    @Override
    public Map<String, Object> queryMPOrderCoupons(AppOrderInfo entity) throws Exception {
        Map<String, Object> result = new HashMap<>(2);
        // 待筛选的优惠券列表
        List<CollectRecord> collectRecords = new LinkedList<>();
        // 1.状态条件,状态为‘已领取’
        String status = "Receive";
        if (MP.equals(entity.getLoginType())) {
            CoreUser user = UserUtil.getUser();
            Account account = accountService.queryById(user.getAcctId());
            // 获取消费者手机号 取该手机号下的优惠卷
            if (StringUtils.isNotBlank(account.getMobilePhone1())) {
                entity.setPhoneNum(account.getMobilePhone1());
            }
        }
        if (StringUtils.isBlank(entity.getPhoneNum())) {
            // 没有手机号只查询的当前客户的优惠券
            CollectRecord collectRecord = new CollectRecord();
            Long accntId = UserUtil.getUser().getId();
            collectRecord.setAccntId(accntId);
            collectRecord.setClaimStatus(status);
            collectRecord.setPageFlag(false);
            collectRecords = collectRecordService.queryByExamplePage(collectRecord);
        } else {
            // 如果订单有手机号码信息，找到当前手机号下的所有客户所拥有的优惠券
            Account accountParam = new Account();
            accountParam.setMobilePhone1(entity.getPhoneNum());
            // 导购助手添加筛选条件
            if (GUIDE_APP.equals(entity.getLoginType())) {
                accountParam.setAcctChannel("Store");
            }
            accountParam.setPageFlag(false);
            List<Account> accountList = accountMapper.queryByExamplePage(accountParam);
            if (accountList.size() > 0) {
                // 把客户列表的所有优惠券添加到collectRecords中，然后筛选
                for (Account account : accountList) {
                    Long accntId = account.getId();
                    CollectRecord collectRecordParam = new CollectRecord();
                    collectRecordParam.setAccntId(accntId);
                    collectRecordParam.setClaimStatus(status);
                    collectRecordParam.setPageFlag(false);
                    List<CollectRecord> tempCollectRecords = collectRecordService.queryByExamplePage(collectRecordParam);
                    collectRecords.addAll(tempCollectRecords);
                }
            } else {
                throw new ServiceException("COUPONS-015", entity.getPhoneNum());
            }
        }
        // 订单包含的产品列表
        List<Product> productList = entity.getProductList();
        // 过滤，排序
        collectRecords = collectRecords
                .stream()
                // 2.时间条件,有效期在当前时间内
                .filter(this::filterTime)
                // 3.适用产品条件,优惠券的适用产品包含订单中的至少一个产品
                .filter(collectRecord -> filterProduct(collectRecord, productList))
                // 4.适用产品总金额条件，即所有适用优惠券的产品价格之和大于优惠券最低使用标准
                .filter(collectRecord -> collectRecord.getProductsPrice() > collectRecord.getAmountLimit())
                // 给优惠券添加实际减免金额属性
                .map(this::addActualCutPrice)
                // 排序
                .sorted(this::sortCollectRecords)
                .collect(Collectors.toList());
        // 过滤后，正常可用的券
        result.put("rows", collectRecords);
        return result;
    }

    /**
     * 根据电话号码判断判断客户是否已经领券
     * @author wangdawei
     * @param couponsList
     * @return
     */
    @Override
    public List<Coupons> checkCoupon(@RequestBody List<Coupons> couponsList, String mobilePhone, Long corpid) throws Exception {
        // 根据客户电话号码带出所有客户
        //无状态登录获取用户信息，默认获取管理员信息
        User user = userService.queryUserByCropId(corpid);
        SecurityInterceptor.tempUser.set(user);
        Account account = new Account();
        account.setMobilePhone1(mobilePhone);
        account.setPageFlag(false);
        List<Account> accountList = accountMapper.queryByExamplePage(account);
        List<Coupons> cList = new ArrayList<>();
        for (Coupons coupons : couponsList) {
            for (Account account1 : accountList) {
                CollectRecord collectRecord = new CollectRecord();
                collectRecord.setAccntId(account1.getId());
                collectRecord.setCouponsId(coupons.getId());
                collectRecord.setPageFlag(false);
                List<CollectRecord> collectRecordList = collectRecordMapper.queryByExamplePage(collectRecord);
                if (collectRecordList.size() > 0) {
                    coupons.setCouponsStuts("R");
                    cList.add(coupons);
                    break;
                }
            }
        }
        return cList;
    }

    /**
     * 判断优惠券是否在有效期内
     * 若有效期为空，认为该优惠券为无期限类型的
     * @author KuangRuifeng
     * @param collectRecord 需要判断是否过期的券
     * @return true: 未过期 false: 已过期
     */
    private Boolean filterTime(CollectRecord collectRecord) {
        // 2.时间条件,有效期在当前时间内
        Date now = new Date();
        String endTimeStr = collectRecord.getEffectEndTime();
        if (StringUtils.isNull(endTimeStr)) {
            return true;
        } else {
            Date effectEndTime = DateUtil.stringToDate(endTimeStr, "yyyy-MM-dd HH:mm:ss");
            return effectEndTime.after(now);
        }
    }

    /**
     * 判断优惠券是否适用于产品列表
     * @author KuangRuifeng
     * @param collectRecord 需要判断是否过期的券
     * @return true: 适用 false: 不适用
     */
    private Boolean filterProduct(CollectRecord collectRecord, List<Product> productList) {
        // 3.适用产品条件,优惠券的适用产品包含订单中的至少一个产品
        // 先计算出所有适用产品的价格之和,存在productsPrice属性中
        try {
            addProductsPrice(collectRecord, productList);
            // 没有适用产品时的价格
            Double signPrice = 0.0;
            return signPrice < collectRecord.getProductsPrice();
        } catch (Exception e) {
            LCLogger.withException(e);
            return false;
        }
    }

    /**
     * 计算出产品列表中所有适用于此优惠券的产品的价格之和
     * 存放在collectRecord的productsPrice属性中，用于比较排序
     * 当值为0.0时，认为产品列表中没有任何一件产品适用此优惠券
     * @author KuangRuifeng
     * @param collectRecord 优惠券
     * @param productList   产品列表
     * @throws Exception 异常
     */
    private void addProductsPrice(CollectRecord collectRecord, List<Product> productList) throws Exception {
        String fitType = collectRecord.getFitProd();
        //  产品列表中适用于此优惠券的所有产品的价格之和，用于比较排序
        Double productsPrice = 0.0;
        // 满足所有产品
        String typeAll = "All";
        // 满足品牌系列
        String typeBrandSeries = "BrandSeries";
        // 满足特定产品
        String typeSpecified = "Specified";
        if (typeAll.equals(fitType)) {
            // a,优惠的适用产品选项为：‘所有产品’
            productsPrice = productList
                    .stream()
                    .mapToDouble(product -> Double.valueOf(product.getAttr2()) * product.getSalePrice())
                    .sum();
        } else if (typeBrandSeries.equals(fitType)) {
            // b,优惠的适用产品选项为：‘按品牌类型’，且产品的品牌包含在‘适用品牌’
            // 多值字段中&产品的类型包含在‘适用产品类型’多值字段中（如果多值字段为空，则代表符合要求)
            BrandSeries bs = new BrandSeries();
            Long couponsId = collectRecord.getCouponsId();
            bs.setCouponsId(couponsId);
            bs.setPageFlag(false);
            // 先查询出优惠券可以使用的所有品牌系列
            List<BrandSeries> brandSeriesList = brandSeriesMapper.queryByExamplePage(bs);
            productsPrice = productList
                    .stream()
                    .filter(product -> prodFitBrandSeries(brandSeriesList, product))
                    .mapToDouble(product -> Double.valueOf(product.getAttr2()) * product.getSalePrice())
                    .sum();
        } else if (typeSpecified.equals(fitType)) {
            // c,优惠的适用产品选项为：‘按具体产品’，且优惠券的‘适用产品’多值字段中，包含订单中的任一产品
            ProCoupons proCoupons = new ProCoupons();
            Long couponsId = collectRecord.getCouponsId();
            proCoupons.setCouponsId(couponsId);
            proCoupons.setPageFlag(false);
            List<ProCoupons> proCouponsList = proCouponsMapper.queryByExamplePage(proCoupons);
            productsPrice = productList
                    .stream()
                    .filter(product -> prodFitSpecified(proCouponsList, product))
                    .mapToDouble(product -> Double.valueOf(product.getAttr2()) * product.getSalePrice())
                    .sum();
        }
        collectRecord.setProductsPrice(productsPrice);
    }

    /**
     * 判断某产品是否适用某优惠券的品牌系列条件
     * @author KuangRuifeng
     * @param proCouponsList 条件
     * @param product        产品
     * @return 满足条件
     */
    private Boolean prodFitSpecified(List<ProCoupons> proCouponsList, Product product) {
        // 如果为空，认为满足
        if (proCouponsList.size() == 0) {
            return true;
        }
        return proCouponsList
                .stream()
                .anyMatch(proCoupons -> proCoupons.getProdId().equals(product.getId()));
    }

    /**
     * 判断某产品是否适用某优惠券的品牌系列条件
     * @author KuangRuifeng
     * @param brandSeriesList 条件
     * @param p               产品
     * @return 满足条件
     */
    private Boolean prodFitBrandSeries(List<BrandSeries> brandSeriesList, Product p) {
        // 如果为空，认为满足
        if (brandSeriesList.size() == 0) {
            return true;
        }
        // 品牌
        String brand = "Brand";
        // 系列
        String series = "Series";
        // 查询出商品的品牌系列等信息
        Product product;
        try {
            product = productService.queryBrandSeriesById(p.getId());
        } catch (Exception e) {
            LCLogger.withException(e);
            return false;
        }
        for (BrandSeries brandSeries : brandSeriesList) {
            // 品牌或者系列类别
            String type = brandSeries.getBrandseriesType();
            if (brand.equals(type)) {
                // 一级品牌
                String prodBrand = brandSeries.getProdFirstBrand();
                // 二级品牌
                String prodSecBrand = brandSeries.getProdSecBrand();
                // 三级品牌
                String prodThirdBrand = brandSeries.getProdThirdBrand();
                // 若优惠券规定的一二三级品牌为空，则默认符合条件，若不为空进一步判断是否符合产品品牌
                boolean result = (StringUtils.isNull(prodBrand) || prodBrand.equals(product.getProdBrand()))
                        && (StringUtils.isNull(prodSecBrand) || prodSecBrand.equals(product.getProdSecBrand()))
                        && (StringUtils.isNull(prodThirdBrand) || prodThirdBrand.equals(product.getProdThirdBrand()));
                if (!result) {
                    return false;
                }
            } else if (series.equals(type)) {
                // 一级系列
                String prodMatSeries = brandSeries.getProdFirstSeries();
                // 二级系列
                String prodSecSeries = brandSeries.getProdSecSeries();
                // 三级系列
                String prodThirdSeries = brandSeries.getPeodThirdSeries();
                // 逻辑判断与‘品牌’相同
                boolean result = (StringUtils.isNull(prodMatSeries) || prodMatSeries.equals(product.getProdMatSeries()))
                        && (StringUtils.isNull(prodSecSeries) || prodSecSeries.equals(product.getProdSecSeries()))
                        && (StringUtils.isNull(prodThirdSeries) || prodThirdSeries.equals(product.getProdThirdSeries()));
                if (!result) {
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 计算实际减免金额
     * @author KuangRuifeng
     * @param collectRecord 优惠券
     */
    private CollectRecord addActualCutPrice(CollectRecord collectRecord) {
        // 优惠券金额
        Double disAmount = collectRecord.getDisAmount();
        // 适用于优惠券的产品金额之和
        Double productsPrice = collectRecord.getProductsPrice();
        // 实际减免金额
        Double actualCutPrice = disAmount > productsPrice ? productsPrice : disAmount;
        collectRecord.setActualCutPrice(actualCutPrice);
        return collectRecord;
    }

    /**
     * 比较优惠券
     * @author KuangRuifeng
     * @param left  优惠券1
     * @param right 优惠券2
     * @return -1: left在前 1: right在前
     */
    private Integer sortCollectRecords(CollectRecord left, CollectRecord right) {
        // 优惠券金额
        Double leftDisAmount = left.getDisAmount();
        Double rightDisAmount = right.getDisAmount();
        // 实际减免金额
        Double leftActualCutPrice = left.getActualCutPrice();
        Double rightActualCutPrice = right.getActualCutPrice();
        if (leftActualCutPrice > rightActualCutPrice) {
            return -1;
        } else if (leftActualCutPrice.equals(rightActualCutPrice)) {
            // 进一步比较,优惠券金额和实际减免金额的差
            BigDecimal bigDecimalLeftDisAmount = new BigDecimal(Double.toString(leftDisAmount));
            BigDecimal bigDecimalLeftActualCutPrice = new BigDecimal(Double.toString(leftActualCutPrice));
            Double leftGap = bigDecimalLeftDisAmount.subtract(bigDecimalLeftActualCutPrice).doubleValue();
            BigDecimal bigDecimalRightDisAmount = new BigDecimal(Double.toString(rightDisAmount));
            BigDecimal bigDecimalRightActualCutPrice = new BigDecimal(Double.toString(rightActualCutPrice));
            Double rightGap = bigDecimalRightDisAmount.subtract(bigDecimalRightActualCutPrice).doubleValue();
            if (leftGap > rightGap) {
                return -1;
            } else if (leftGap.equals(rightGap)) {
                // 进一步比较，优惠券过期时间
                String leftEndTimeStr = left.getEffectEndTime();
                String rightEndTimeStr = right.getEffectEndTime();
                // 限定转化时间的字符串长度
                int subFlag = 19;
                // 截取多余字符
                if (leftEndTimeStr.length() > subFlag) {
                    leftEndTimeStr = leftEndTimeStr.substring(0, subFlag);
                }
                if (rightEndTimeStr.length() > subFlag) {
                    rightEndTimeStr = rightEndTimeStr.substring(0, subFlag);
                }
                Date leftEndTime = DateUtil.stringToDate(leftEndTimeStr, "yyyy-MM-dd HH:mm:ss");
                Date rightEndTime = DateUtil.stringToDate(rightEndTimeStr, "yyyy-MM-dd HH:mm:ss");
                // 比较时间
                if (leftEndTime.after(rightEndTime)) {
                    return -1;
                } else if (leftEndTime.before(rightEndTime)) {
                    return 1;
                } else {
                    return 0;
                }
            } else {
                return 1;
            }
        } else {
            return 1;
        }
    }

    /**
     * 保存红包活动
     *
     * @param coupons
     * @return
     * @throws Exception
     */
    @Transactional(rollbackFor = ServiceException.class)
    @Override
    public Map<String, Object> createdRedPackActivity(Coupons coupons) throws Exception {
        Map<String, Object> map = new HashMap<>(4);
        String status = "NEW";
        //如果是新建的话，insert
        if (StringUtils.equals(coupons.getRow_status(), status)) {
            // 获取红包活动背景图id
            String backGroundImageId = PropertyUtil.getCropProperty("redPacketCampPicId", UserUtil.getUser().getCorpid());
            SaleActivity saleActivity = new SaleActivity();
            // 获取红包活动背景图id
            saleActivity.setAtyPicBackId(Long.parseLong(backGroundImageId));
            //活动名称
            saleActivity.setActivityName(coupons.getCouponsName());
            //开始时间
            saleActivity.setActivityStartDate(coupons.getEffectStaTime());
            //结束时间
            saleActivity.setActivityEndDate(coupons.getEffectEndTime());
            // 规则
            saleActivity.setIntroduction(coupons.getInstru());
            //活动类型
            saleActivity.setActivityType(coupons.getAttr1());
            // 活动大类
            saleActivity.setActivityClass(coupons.getAttr2());
            // 活动状态
            saleActivity.setActivityState(coupons.getAttr3());
            saleActivityService.insert(saleActivity);
            coupons.setActivityId(saleActivity.getId());
            this.insert(coupons);
        } else {
            couponsMapper.update(coupons);
            SaleActivity saleActivity = new SaleActivity();
            saleActivity.setId(coupons.getActivityId());
            saleActivity = saleActivityService.queryById(saleActivity);
            if (null != saleActivity) {
                saleActivity.setActivityName(coupons.getCouponsName());
                saleActivity.setActivityStartDate(coupons.getEffectStaTime());
                saleActivity.setActivityEndDate(coupons.getEffectEndTime());
                saleActivity.setIntroduction(coupons.getInstru());
                saleActivity.setActivityType(coupons.getAttr1());
                saleActivity.setActivityClass(coupons.getAttr2());
                saleActivity.setActivityState(coupons.getAttr3());
                saleActivityService.update(saleActivity);
            }
        }
        return map;
    }

    /**
     * 查询红包详情
     * @author 路江
     * @param coupons
     * @return
     * @throws Exception
     */
    @Override
    public Map<String, Object> queryRedPackActivity(Coupons coupons) throws Exception {
        Map<String, Object> map = new HashMap<>(4);
        // 查询红包详情
        SaleActivity saleActivity = new SaleActivity();
        saleActivity.setId(coupons.getId());
        saleActivity = saleActivityService.queryById(saleActivity);
        Coupons entity = new Coupons();
        if (null != saleActivity) {
            // 红包活动详情
            entity.setActivityId(saleActivity.getId());
            entity.setPageFlag(false);
            List<Coupons> list = this.queryByExamplePage(entity);
            if (list.size() > 0) {
                entity = list.get(0);
            }
            entity.setAttr1(saleActivity.getActivityType());
            entity.setAttr2(saleActivity.getActivityClass());
            entity.setAttr3(saleActivity.getActivityState());
        }
        map.put("row", entity);
        return map;
    }
}
